import { Fragment } from 'react'
import classNames from 'classnames'
import Widget from './widget'
import { isUndefined, isFunction, isArray } from 'loadsh'
import styles from './index.module.less'

const Layout = ({ options, value = {}, rootValue, onChange }) => {
  const offsetLeft = (offset = 1) => ({ marginLeft: `${offset * 24}px` })

  const onLayoutChange = (key, layoutValue) => {
    const newValue = {
      ...value,
      [key]: layoutValue
    }
    onChange(newValue)
  }

  const isVisible = ({ when }) => {
    return isUndefined(when) || (isFunction(when) && when(value, rootValue))
  }

  const isOptionsVisible = ({ options }) => {
    if (isArray(options)) {
      return options.filter((opt) => isVisible(opt))
    }
    return options
  }

  const widgetProps = (props) => {
    props = { ...props }
    delete props.when
    props.style = props.offset && offsetLeft(props.offset)
    if (props.options) {
      props.options = isOptionsVisible(props)
    }
    return props
  }

  return (
    <>
      {Object.entries(options).map(([key, item]) => (
        <Fragment key={key}>
          {isVisible(item) ? (
            <>
              {item?.type === 'object' ? (
                <div
                  className={classNames(styles['children'], styles[item.layout || 'horizontal'])}
                  style={offsetLeft(item.offset)}
                >
                  {item.label ? <label className={styles['label']}>{item.label}</label> : null}
                  <div className={styles['child-layout']}>
                    <Layout
                      options={item.options}
                      value={value[key]}
                      rootValue={rootValue}
                      onChange={(value) => onLayoutChange(key, value)}
                    />
                  </div>
                </div>
              ) : (
                <Widget
                  {...widgetProps(item)}
                  value={value[key]}
                  onChange={(value) => onLayoutChange(key, value)}
                />
              )}
            </>
          ) : null}
        </Fragment>
      ))}
    </>
  )
}

export default Layout
